package com.ming.service.impl;

import com.ming.dao.UserDao;
import com.ming.po.ResponseBean;
import com.ming.po.User;
import com.ming.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao ud;

	/**
	 * 查询验证登录信息
	 * @param user
	 * @return
	 */
	@Override
	public ResponseBean<User> getUserByIdByPass(User user) {
		User result = ud.getUserByIdByPass(user);
		ResponseBean<User> rb;
		if(result!=null){
			result.setPassword("");
			rb = new ResponseBean<>(result);
		}else{
			rb = new ResponseBean<>(602,"用户名或密码不正确");
		}
		return rb;
	}

	/**
	 * 通过用户Id查询用户
	 * @param userId
	 * @return
	 */
	@Override
	public ResponseBean<User> getUserById(String userId) {
		User user = ud.getUserById(userId);
		ResponseBean<User> rb;
		if(user!=null){
			user.setPassword("");
			rb = new ResponseBean<>(user);
		}else{
			rb = new ResponseBean<>(602,"用户不存在");
		}
		return rb;
	}

	/**
	 * 注册保存用户
	 * @param user
	 * @return
	 */
	@Override
	@Transactional
	public ResponseBean<Integer> saveUser(User user) {
		int result = ud.saveUser(user);
		ResponseBean<Integer> rb;
		if(result!=0){
			rb = new ResponseBean<>(result);
		}else{
			rb = new ResponseBean<>(603,"注册失败");
		}
		return rb;
	}

	/**
	 * 更改用户头像
	 * @param user
	 * @return
	 */
	@Override
	@Transactional
	public ResponseBean<Integer> updateUserImg(User user) {
		int result = ud.updateUserImg(user);
		ResponseBean<Integer> rb;
		if(result!=0){
			rb = new ResponseBean<>(result);
		}else{
			rb = new ResponseBean<>(603,"更新照片失败");
		}
		return rb;
	}

	/**
	 * 更改用户密码
	 * @param user
	 * @return
	 */
	@Override
	public ResponseBean<Integer> updatePwd(User user) {
		int result = ud.updatePwd(user);
		ResponseBean<Integer> rb;
		if(result!=0){
			rb = new ResponseBean<>(result);
		}else{
			rb = new ResponseBean<>(603,"修跟改密码失败");
		}
		return rb;
	}

	/**
	 * 查询密码是否与原密码相同
	 * @param user
	 * @return
	 */
	@Override
	public ResponseBean<Integer> isSameOldPwd(User user) {
		int result = 0;
		User oldUser = ud.getUserById(user.getUserId());
		// 判断原密码与请求密码是否一致
		if(oldUser!=null){
			if(user.getPassword().equals(oldUser.getPassword())){
				result = 1;
			}
		}
		return new ResponseBean<>(result);
	}
}
